package com.tky.conference.ui;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.TimePopupWindow;
import com.tky.conference.R;
import com.tky.conference.base.BaseActivity;
import com.tky.conference.base.BaseApplication;
import com.tky.conference.dao.AppointInfo;
import com.tky.conference.dao.DeptInfo;
import com.tky.conference.dao.HysInfo;
import com.tky.conference.dao.TreeInfo;
import com.tky.conference.entity.FailRequest;
import com.tky.conference.implInterfaces.AddUpdateImpl;
import com.tky.conference.interfaces.HttpResultListener;
import com.tky.conference.utlils.ShowDialog;
import com.tky.conference.utlils.ToastUtil;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by yy on 2015/12/16.
 */
public class UpdateActivity extends BaseActivity implements View.OnClickListener{
    private List<String> hysList = new ArrayList<>();
    private List<String> deptList = new ArrayList<>();
    private AppointInfo appointInfo;
    private Toolbar toolbar;
    private EditText subject,prepare,discribe;
    private TextView startTime,endTime,attend,respons,record,destination;
    private Spinner spinnerAddress,spinnerDept;
    private CheckBox isMessage,jst;
    private Button update;
    TimePopupWindow pwStartTime,pwEndTime;
    private String stime,etime;
    private List<TreeInfo> treeInfoList;
    private List<HysInfo> hysInfoList;
    private List<DeptInfo> deptInfoList;
    private String recordId,recordName,responsId,responsName,attendId,attendName,account,hysId,hydd;
    //申请部门
    private String deptName,currentId;
    private int lastSelect,defaultSelect;
    private ShowDialog showDialog;

    @Override
    public void initView() {
        setContentView(R.layout.activity_update);
        subject= (EditText) findViewById(R.id.et_subject);
        prepare= (EditText) findViewById(R.id.et_prepare);
        discribe= (EditText) findViewById(R.id.et_discribe);
        startTime= (TextView) findViewById(R.id.tv_startTime);
        endTime= (TextView) findViewById(R.id.tv_endTime);
        attend= (TextView) findViewById(R.id.tv_attend);
        respons= (TextView) findViewById(R.id.tv_respons);
        record= (TextView) findViewById(R.id.tv_record);
        spinnerAddress= (Spinner) findViewById(R.id.spinner_address);
        spinnerDept= (Spinner) findViewById(R.id.spinner_dept);
        destination= (TextView) findViewById(R.id.tv_destination);
        isMessage= (CheckBox) findViewById(R.id.message);
        jst= (CheckBox) findViewById(R.id.jst);
        update= (Button) findViewById(R.id.bt_update);
    }

    @Override
    public void initDates() {
        showDialog=new ShowDialog(UpdateActivity.this);
        SharedPreferences sp=this.getSharedPreferences("save_account",MODE_PRIVATE);
        account=sp.getString("account",null);

        appointInfo= (AppointInfo) getIntent().getSerializableExtra("APPINFO");
        currentId=appointInfo.getId();
        //申请部门
        deptName=appointInfo.getZbbm();

        treeInfoList=(List<TreeInfo>) getIntent().getSerializableExtra("TREELIST");
        hysInfoList=(List<HysInfo>) getIntent().getSerializableExtra("HYSLIST");


        for (int i=0;i<hysInfoList.size();i++){
            if (hysInfoList.get(i).getPid().equals(appointInfo.getHysmc())){
                defaultSelect=i;
            }
            hysList.add(hysInfoList.get(i).getPid());
        }

        deptInfoList=(List<DeptInfo>) getIntent().getSerializableExtra("DEPTLIST");
        for (int i=0;i<deptInfoList.size();i++){
            if(deptInfoList.get(i).getName().equals(deptName)){
                lastSelect=i;
            }
            deptList.add(deptInfoList.get(i).getName());
        }


        subject.setText(appointInfo.getHyzt());
        discribe.setText(appointInfo.getHyms());
        startTime.setText(appointInfo.getStime());
        endTime.setText(appointInfo.getEtime());
        attend.setText(appointInfo.getChry());
        record.setText(appointInfo.getJlr());
        respons.setText(appointInfo.getFzr());
        destination.setText(hysInfoList.get(defaultSelect).getName());
        //如果不再次选择列表 就是如下默认值
        recordName=appointInfo.getJlr();
        recordId=appointInfo.getJlrid();
        responsName=appointInfo.getFzr();
        responsId=appointInfo.getFzrid();

        attendName=appointInfo.getChry();
        attendId=appointInfo.getChryid();
        //默认选项
        hysId=appointInfo.getHysid();
        hydd=appointInfo.getHydd();
        deptName=appointInfo.getZbbm();
        //默认时间选项
        stime=appointInfo.getStime();
        etime=appointInfo.getEtime();
    }

    @Override
    public void initToolBar() {
        toolbar= (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setTitle("修改会议 ");
    }

    @Override
    public void initEvent() {

        initAddSpinner();
        initDeptSpinner();
        //时间接口的回调
        pwStartTime = new TimePopupWindow(this, TimePopupWindow.Type.ALL);
        //时间选择后的回调
        pwStartTime.setOnTimeSelectListener(new TimePopupWindow.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date) {
                if (getMillisTime(date) + (60 * 1000) <= System.currentTimeMillis()) {
                    Toast.makeText(BaseApplication.getContext(), "请输入合适时间", Toast.LENGTH_LONG).show();
                    startTime.setText("请点击");
                } else if (!startTime.getText().toString().equals("请点击") && !endTime.getText().toString().equals("请点击")) {
                    if (getMillisTime(endTime.getText().toString()) < getMillisTime(date)) {
                        Toast.makeText(BaseApplication.getContext(), "请输入合适时间", Toast.LENGTH_LONG).show();
                        startTime.setText(getTime(date));
                        endTime.setText("请点击");
                    } else if (getMillisTime(endTime.getText().toString()) > getMillisTime(date)) {
                        startTime.setText(getTime(date));
                    } else if (getMillisTime(endTime.getText().toString()) == getMillisTime(date)) {
                        Toast.makeText(BaseApplication.getContext(), "时间不能相同", Toast.LENGTH_LONG).show();
                        startTime.setText("请点击");
                    }
                } else {
                    startTime.setText(getTime(date));

                }
                stime=startTime.getText().toString();
            }


        });

        pwEndTime = new TimePopupWindow(this, TimePopupWindow.Type.ALL);
        //时间选择后的回调
        pwEndTime.setOnTimeSelectListener(new TimePopupWindow.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date) {
                if (startTime.getText().toString().equals("请点击")) {
                    Toast.makeText(BaseApplication.getContext(), "请输入开始时间", Toast.LENGTH_LONG).show();
                } else {
                    if (getMillisTime(startTime.getText().toString()) > getMillisTime(date)) {
                        Toast.makeText(BaseApplication.getContext(), "请输入合适时间", Toast.LENGTH_LONG).show();
                        endTime.setText("请点击");
                    } else if (startTime.getText().toString().equals(getTime(date))) {
                        Toast.makeText(BaseApplication.getContext(), "时间不能相同", Toast.LENGTH_LONG).show();
                        endTime.setText("请点击");
                    } else {
                        endTime.setText(getTime(date));
                    }
                }

                etime = endTime.getText().toString();
            }
        });

        isMessage.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                Toast.makeText(BaseApplication.getContext(), "暂不支持短信", Toast.LENGTH_LONG).show();
                isMessage.setChecked(false);
            }
        });
        startTime.setOnClickListener(this);
        endTime.setOnClickListener(this);
        record.setOnClickListener(this);
        attend.setOnClickListener(this);
        respons.setOnClickListener(this);
        update.setOnClickListener(this);
    }

    private void initDeptSpinner() {
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, deptList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerDept .setAdapter(adapter);
        spinnerDept.setSelection(lastSelect, true);
        spinnerDept.setOnItemSelectedListener(new SpinnerDeptListener());
    }

    private void initAddSpinner() {
        // 建立Adapter并且绑定数据源
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, hysList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //绑定 Adapter到控件
        spinnerAddress.setAdapter(adapter);
        spinnerAddress.setSelection(defaultSelect,true);
        //添加事件Spinner事件监听

        spinnerAddress.setOnItemSelectedListener(new SpinnerAddressListener());
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_startTime:
                pwStartTime.setCyclic(true);
                pwStartTime.showAtLocation(startTime, Gravity.BOTTOM, 0, 0, new Date());
                break;
            case R.id.tv_endTime:
                pwEndTime.setCyclic(true);
                pwEndTime.showAtLocation(endTime, Gravity.BOTTOM, 0, 0, new Date());
                break;
            case R.id.tv_record:
                Intent intent=new Intent(UpdateActivity.this,TreeActivity.class);
                intent.putExtra("TREELIST",(Serializable) treeInfoList);
                startActivityForResult(intent,10);
                break;
            case R.id.tv_respons:
                Intent intent2=new Intent(UpdateActivity.this,TreeActivity.class);
                intent2.putExtra("TREELIST",(Serializable) treeInfoList);
                startActivityForResult(intent2,11);
                break;
            case R.id.tv_attend:
                Intent intent3=new Intent(UpdateActivity.this,TreeActivity.class);
                intent3.putExtra("TREELIST",(Serializable) treeInfoList);
                startActivityForResult(intent3,12);
                break;
            case R.id.bt_update:
                //开始条件
                //提交数据
                boolean isAll=isEmpty();
                if (isAll){
                    //如果正确开始访问网络
                    AddUpdateImpl addUpdateImpl=new AddUpdateImpl(new UpdateHttpResultListener());
                    addUpdateImpl.addUpdate(account, hysId, recordId, recordId, attendId, stime, etime, hydd,
                            subject.getText().toString(), discribe.getText().toString(),
                            deptName, prepare.getText().toString(), currentId, "");
                    System.out.print("d");
                }else {
                    ToastUtil.showToast(this, "请确保填写完整");
                }
        }
    }

    class UpdateHttpResultListener implements HttpResultListener{

        @Override
        public void onStartRequest() {
            showDialog.Loading("正在修改...");
        }

        @Override
        public void onResult(Object obj) {
            if (obj instanceof FailRequest) {
                showDialog.dismissDialog();
                if (!((FailRequest) obj).getStatus().equals(0)) {
                    ToastUtil.showToast(UpdateActivity.this, ((FailRequest) obj).getMsg());
                }
            } else {
                Intent intent=getIntent();
                AppointInfo appointInfo=new AppointInfo();
                appointInfo.setHyzt(subject.getText().toString());
                appointInfo.setHysmc(hydd);
                appointInfo.setHydd(destination.getText().toString());
                appointInfo.setFzr(responsName);
                appointInfo.setJlr(recordName);
                appointInfo.setChry(attendName);
                appointInfo.setSqr(account);
                appointInfo.setEtime(etime);
                appointInfo.setStime(stime);
                appointInfo.setStatus("1");
                appointInfo.setChryid(attendId);
                appointInfo.setFzrid(responsId);
                appointInfo.setJlrid(recordId);
                appointInfo.setHyms(discribe.getText().toString());
                appointInfo.setHysid(hysId);
                appointInfo.setMessage("2");
                appointInfo.setId(currentId);
                appointInfo.setCreateat("");
                appointInfo.setOrgid("");
                appointInfo.setUseflag("");
                Bundle bundle =new Bundle();
                bundle.putSerializable("appinfo",appointInfo);
                intent.putExtras(bundle);
                showDialog.dismissDialog();
                setResult(0, intent);
                UpdateActivity.this.finish();
            }
        }

        @Override
        public void onFinish() {

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data!=null){
            switch (requestCode){
                case 10:
                    //记录人员
                    recordId=data.getStringExtra("id");
                    recordName=data.getStringExtra("name");
                    record.setText(recordName);
                    break;
                case 11:
                    //负责人员
                    responsId=data.getStringExtra("id");
                    responsName=data.getStringExtra("name");
                    respons.setText(responsName);
                    break;
                case 12 :
                    //参会人员
                    attendId=data.getStringExtra("id");
                    attendName=data.getStringExtra("name");
                    attend.setText(attendName);
                    break;
            }
        }
    }

    //spinner点击事件
    class SpinnerAddressListener implements AdapterView.OnItemSelectedListener {

        public void onItemSelected(AdapterView<?> arg0, View arg1, int position,
                                   long l) {

            destination.setText(hysInfoList.get(position).getName());
            hydd=destination.getText().toString();
            hysId=hysInfoList.get(position).getId();
        }

        public void onNothingSelected(AdapterView<?> arg0) {

        }
    }
    //spinner点击事件
    class SpinnerDeptListener implements AdapterView.OnItemSelectedListener {

        public void onItemSelected(AdapterView<?> arg0, View arg1, int i,
                                   long l) {

            deptName=deptInfoList.get(i).getName();
        }

        public void onNothingSelected(AdapterView<?> arg0) {

        }
    }






    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();
        if(id==android.R.id.home){
            this.finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    //日期转换成字符串
    public static String getTime(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return format.format(date);
    }

    //日期转换成毫秒值
    public static long getMillisTime(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String choseTime = format.format(date);
        try {
            return format.parse(choseTime).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }
    //日期类型的字符串转换成毫秒值
    public static long getMillisTime(String date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            return format.parse(date).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public boolean isEmpty(){
        if (!TextUtils.isEmpty(subject.getText().toString())&& !TextUtils.isEmpty(prepare.getText().toString())&& !TextUtils.isEmpty(discribe.getText().toString())
                &&!recordName.equals("")&& !recordName.equals("")&& !attendName.equals("")&&!TextUtils.isEmpty(endTime.getText().toString())&&
                !TextUtils.isEmpty(startTime.getText().toString()))
        {
            return true;
        }else {
            return false;
        }

    }
}
